import Vue from "vue";

import Vuex from "vuex";
import {
  getRequest,
  postRequest,
  deleteRequest,
  putRequest,
} from "../utils/request";

import local from "./local";

Vue.use(Vuex);

const store = new Vuex.Store({
  state: {
    token: null,
    userInfo: null,
    routes: [], //菜单路由
  },
  getters: {},
  mutations: {
    SET_USERINFO: (state, userInfo) => {
      state.userInfo = userInfo;
    },
    SET_TOKEN: (state, token) => {
      state.token = token;
    },
    initRoutes(state, data) {
      state.routes = data;
    },
  },
  actions: {
    //登录的请求
    login({ commit }, loginUser) {
      return new Promise((resolve, reject) => {
        postRequest("/login", loginUser)
          .then((res) => {
            console.log(res, "----login");
            if (res.code == 200) {
              //返回的code为200，即成功
              const token = res.obj.token;
              console.log(token, "token");
              commit("SET_TOKEN", token);

              const data = res.obj;
              console.log(data);
              commit("SET_USERINFO", data);

              // 存储数据到localStorage
              local.setToken(token);
              local.setUserInfo(data);
            }
            resolve(res);
          })
          .catch((err) => {
            reject(err);
          });
      });
    },
    //获取菜单的请求
    getMenus({ commit }) {
      return new Promise((resolve, reject) => {
        //发送给请求
        getRequest("/menu/queryByUser").then((res) => {
          if (res) {
            console.log(res, "res==菜单");
            resolve(res);
          }
        });
      });
    },
  },
});

export default store;
